//
//  SearchViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/30.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit


class SearchViewController: BaseViewController {
    var displayTable:UITableView!
    var keywords:[NSDictionary] = []
    var noteInfo:UILabel!
    var searchBar:UISearchBar!
    var tableDataSource:[GoodDetailItem] = []
    var menuView:UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = lightBackgoundColor
        searchBar = UISearchBar(frame: CGRectMake(10, 22, view.bounds.size.width-10-40, 40))
        searchBar.searchBarStyle = UISearchBarStyle.Prominent
        searchBar.placeholder = "女神新装"
        if let aview = searchBar.subviews[0] as? UIView{
            if aview.subviews.count>0{
                aview.subviews[0].removeFromSuperview()
            }
        }
        searchBar.becomeFirstResponder()
        searchBar.delegate = self
        navigationItem.titleView = searchBar
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.backgroundColor = UIColor.whiteColor()
//        noteInfo = UILabel(frame: CGRectMake(10,74, 200,25))
////        noteInfo.textColor = commonRedColor
//        noteInfo.font = UIFont.boldSystemFontOfSize(13)
//        view.addSubview(noteInfo)
//        self.createTableView()
        self.queryHotKeyWord()
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(animated: Bool){
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
    }
    func createTableView(){
        //        leftTableDataSource.addObjectsFromArray(["热门品牌","食品/保健","美妆个护","母婴用品","服饰鞋包","生活数码"])
        displayTable = UITableView(frame: CGRectMake(0, CGRectGetMaxY(menuView.frame)+5, view.bounds.size.width, view.bounds.size.height-CGRectGetMaxY(menuView.frame)-5), style: UITableViewStyle.Plain)
        displayTable.backgroundColor = UIColor.clearColor();
        displayTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "historyCell")
        displayTable.separatorStyle = UITableViewCellSeparatorStyle.None
        displayTable.showsHorizontalScrollIndicator = false
        displayTable.showsVerticalScrollIndicator = false
        displayTable.dataSource = self
        displayTable.delegate = self
        displayTable.scrollEnabled = false
        view.addSubview(displayTable)
    }
    func queryHotKeyWord()->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        request.requestStart("/search/getHotWords", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    if let array = dic?["data"]?["key"] as? [NSDictionary]{
                        self.keywords = array
                    }
                    dispatch_async(dispatch_get_main_queue()){
                        self.setupKeyWordView()
                        self.createTableView()
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), {[weak self] in
                        self?.showTips(dic?["msg"] as? String)
                        })
                    
                }
                
            }
            else{
                dispatch_async(dispatch_get_main_queue()){
                }
            }
            
        })
        self.showProcess("加载中...")
    }
    func setupKeyWordView(){
        if self.keywords.count == 0{
            return
             menuView = UIView(frame:CGRectZero)
        }
        let numbersPerRow:NSInteger = view.bounds.size.width>320 ? 4 : 3
        let numbersOfRow:NSInteger = self.keywords.count / numbersPerRow
        let originX:CGFloat = 10.0
        let originY:CGFloat = 33.0
        let distanceX:CGFloat = 20.0
        let distanceY:CGFloat = 15.0
        let height:CGFloat = 27.0
        let width = (view.bounds.size.width - originX*CGFloat(2) - distanceX*CGFloat(numbersPerRow - 1)) / CGFloat(numbersPerRow)
         menuView = UIView(frame: CGRectMake(0, 74, view.bounds.size.width, 30.0 + originY + (distanceY + height)*CGFloat(numbersOfRow)+10))
        menuView.backgroundColor = UIColor.clearColor()
        view.addSubview(menuView)
        let lbl = UILabel(frame: CGRectMake(10, 0, 100, 30))
        lbl.font = UIFont.systemFontOfSize(14)
        lbl.text = "热门搜索"
        menuView.addSubview(lbl)
        for i in 0..<self.keywords.count{
            let dic = self.keywords[i]
            let indexX = i / numbersPerRow
            let indexY = i % numbersPerRow
            let rect = CGRectMake(originX+(width + distanceX)*CGFloat(indexY), originY+(height + distanceY)*CGFloat(indexX), width, height)
            let button = UIButton(frame: rect)
            button.tag = i
            button.backgroundColor = UIColor.whiteColor()
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
            button.titleLabel?.font = UIFont.systemFontOfSize(12)
            button.setTitle(dic["keyname"] as? String, forState: UIControlState.Normal)
            button.layer.cornerRadius = 5.0
            button.layer.borderWidth = onePix
            button.layer.borderColor = UIColor.darkGrayColor().CGColor
            button.addTarget(self, action: "search:", forControlEvents: UIControlEvents.TouchUpInside)
            menuView.addSubview(button)
        }
    }
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    func  search(button:UIButton){
        let ctl = SearchResultViewController()
        ctl.keyword = button.titleLabel?.text
        GlobalDataHelper.instance.saveToSearchHistroy(button.titleLabel?.text)
        ctl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctl, animated: true)
        displayTable.reloadData()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension SearchViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if let array =  GlobalDataHelper.instance.searchHistroyArray{
            return array.count
        }
        return 0
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 20
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let headView = UIView(frame: CGRectMake(0, 0, tableView.bounds.size.width, 20))
        let lbl = UILabel(frame: CGRectMake(10, 0, headView.bounds.size.width - 10, 20))
        lbl.text = "搜索历史"
        lbl.font = UIFont.systemFontOfSize(14)
        headView.addSubview(lbl)
        return headView
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("historyCell", forIndexPath: indexPath)
        cell.contentView.backgroundColor = UIColor.clearColor()
        cell.textLabel?.frame = cell.contentView.bounds
        cell.textLabel?.textColor = UIColor.darkGrayColor()
        cell.textLabel?.textAlignment = NSTextAlignment.Left
        if let array = GlobalDataHelper.instance.searchHistroyArray{
            cell.textLabel?.text = array[indexPath.row] as String
        }
        cell.textLabel?.font = UIFont.systemFontOfSize(12)
        cell.selectionStyle = UITableViewCellSelectionStyle.Gray
        cell.accessoryType = UITableViewCellAccessoryType.None
        let sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(cell.contentView.frame), cell.contentView.bounds.size.width, onePix))
        sepView.backgroundColor = commonBackgoundColor
        cell.contentView.addSubview(sepView)
        return cell;
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        return 30
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){

        searchBar.resignFirstResponder()
        let ctl = SearchResultViewController()
        if let array = GlobalDataHelper.instance.searchHistroyArray{
             ctl.keyword = array[indexPath.row] as String
        }
        GlobalDataHelper.instance.saveToSearchHistroy(searchBar.text)
        ctl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctl, animated: true)
        displayTable.reloadData()
    }
    
}
extension SearchViewController:UISearchBarDelegate{
    func searchBarSearchButtonClicked(searchBar: UISearchBar){
        searchBar.resignFirstResponder()
        let ctl = SearchResultViewController()
        ctl.keyword = searchBar.text
        GlobalDataHelper.instance.saveToSearchHistroy(searchBar.text)
        ctl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctl, animated: true)
        displayTable.reloadData()
    }
}